package com.authine.cloudpivot.web.api.service.impl;
import cn.hutool.http.HttpUtil;
import com.authine.cloudpivot.web.api.dao.OrgUserMapper;
import com.authine.cloudpivot.web.api.domain.Constants;
import com.authine.cloudpivot.web.api.service.CheckUserService;
import com.authine.cloudpivot.web.sso.exception.AccessTokenInvalidateException;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class CheckUserServiceImpl implements CheckUserService {

    @Autowired
    private OrgUserMapper orgUserMapper;

    @Value("${wechatsso.corpid}")
    private String corpid;

    @Value("${wechatsso.corpsecret}")
    private String corpsecret;

    @Value("${wechatsso.tokenUrl}")
    private String tokenUrl;

    @Value("${wechatsso.userInfoUrl}")
    private String userInfoUrl;

    @Value("${wechatsso.userUrl}")
    private String userUrl;

    @Value("${websso.clientId}")
    private String clientId;

    @Value("${websso.clientSecret}")
    private String clientSecret;

    @Value("${websso.webTokenUrl}")
    private String webTokenUrl;

    @Value("${websso.webUserUrl}")
    private String webUserUrl;

    @Value("${websso.granttype}")
    private String granttype;

    @Value("${websso.redirecturi}")
    private String redirecturi;


    @Override
    public String checkUser(String email){
       String userObjectId =orgUserMapper.selectMobileByEmail(email);
       return userObjectId;
     };


    @Override
    public String getAccessToken(String code,String type){
        log.info("进入getAccessToken方法，参数code为：" + code);
        Map<String,Object> param = new HashMap<>();

        String realTokenUrl="";
        String token="";
        if(Constants.WECHAT.equals(type)){
            //企业微信的CORPID
            param.put("corpid",corpid);
            //微信对应secret
            param.put("corpsecret",corpsecret);
            realTokenUrl=tokenUrl;
        }else if(Constants.WEBSSO.equals(type)){
            //WEBSSO
            param.put("grant_type",granttype);
            param.put("client_id",clientId);
            param.put("client_secret",clientSecret);
            param.put("code",code);
            param.put("redirect_uri",redirecturi);
            realTokenUrl=webTokenUrl;
        }

        String response = HttpUtil.get(realTokenUrl, param);

        if(StringUtils.isNotEmpty(response)){
            JSONObject jsonObject = JSONObject.fromObject(response);
            log.info("获取accessToken响应: "+response);
            token = jsonObject.get("access_token")==null?null:String.valueOf(jsonObject.get("access_token"));
            if (StringUtils.isBlank(token)) {
                log.warn("获取accessToken失败，错误信息：" + response);
                throw new AccessTokenInvalidateException(" accessToken 非法");
            }
            log.info("获取Token成功: {}", token);
            log.info("------------------getAccessToken end ----------------------------" );
        }

        return token;
    };



    /**
     * @Description : 企业微信单点登录
     * @param ： code
     * @author : Liun
     * @date : 2020/8/19
     */
    @Override
    public String getSourceId(String code){
        String sourceId="";
        String accessToken = getAccessToken(code, Constants.WECHAT);
        if(StringUtils.isNotEmpty(accessToken)){
            Map<String,Object> param = new HashMap<>(4);
            param.put("access_token",accessToken);
            param.put("code",code);
            String response = HttpUtil.get(userInfoUrl, param);
            log.info("返回结果： " + response);
            JSONObject jsonObject = JSONObject.fromObject(response);
            String userId = jsonObject.get("UserId")==null?null:String.valueOf(jsonObject.get("UserId"));
            log.info("从企业微信查询的的UserId为：" + userId);

            if(!StringUtils.isBlank(userId)){
                Map<String,Object> paramUser = new HashMap<>(4);
                paramUser.put("access_token",accessToken);
                paramUser.put("userid",userId);
                String responseUser = HttpUtil.get(userUrl, paramUser);
                JSONObject jsonObjectUser = JSONObject.fromObject(responseUser);
                String email = jsonObjectUser.get("email")==null?null:String.valueOf(jsonObjectUser.get("email"));
                log.info("从企业微信获取的email为：" + email);
                sourceId =this.checkUser(email);
            }

            if (StringUtils.isBlank(sourceId)) {
                log.warn("获取用户关联信息失败，失败响应："+response);
            }
            log.info("---------------------------getSourceId   end ---------------------------------");
        }
        return sourceId;
    };


    @Override
    public  String getWebSourceId(String code){
        String sourceId="";
        String accessToken = getAccessToken(code, Constants.WEBSSO);
        if(StringUtils.isNotEmpty(accessToken)){
            Map<String,Object> paramUser = new HashMap<>(4);
            paramUser.put("access_token",accessToken);
            String responseUser = HttpUtil.get(webUserUrl, paramUser);
            JSONObject jsonObjectUser = JSONObject.fromObject(responseUser);
            log.info("获取的jsonObjectUser为：" + jsonObjectUser.toString());
            String email = jsonObjectUser.get("id")==null?null:String.valueOf(jsonObjectUser.get("id"));
            log.info("获取的email为：" + email);
            sourceId =this.checkUser(email);
        }
        return sourceId;
    };







}



